package com.sharkburner.common.dao.paginator;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class LazyCriteriaFactory implements LazyFactory, Serializable {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    private Criteria listCriteria;
    private Criteria countCriteria;
    private int size = 0;

    @Override
    public int getSize() {
	return size;
    }

    @Override
    public List<Object> getList(int startIndex, int count) {
	listCriteria.setFirstResult(startIndex);
	listCriteria.setMaxResults(count);

	return listCriteria.list();
    }

    @Override
    public void setDataProvider(Object data) {
	DetachedCriteria detachedCriteria = (DetachedCriteria) data;

	Session session = hibernateTemplate.getSessionFactory().openSession();
	DetachedCriteria countDetachedCriteria = (DetachedCriteria) PaginationFactory
		.cloneDataProvider(detachedCriteria);
	listCriteria = detachedCriteria.getExecutableCriteria(session);

	countCriteria = countDetachedCriteria.getExecutableCriteria(session);
	countCriteria.setProjection(Projections.rowCount());

	size = (Integer) countCriteria.uniqueResult();
    }

}
